﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MVCClient.Models;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Hosting;

namespace MVCClient.Controllers
{
    
    public class UploadFileController : Controller
    {
        private IHostingEnvironment hostingEnv;
        public UploadFileController(IHostingEnvironment hosting)
        {
            hostingEnv = hosting;
        }


        public IActionResult Index()
        {
            return View();
        }
        [HttpPost("UploadFiles")]
        public IActionResult UploadFiles()
        {
            var form = HttpContext.Request.Form;
            var files = form.Files;
            long size = 0;
            foreach (var file in files)
            {
                //var fileName = file.FileName;
                var fileName = ContentDispositionHeaderValue
                                .Parse(file.ContentDisposition)
                                .FileName
                                .Trim('"');
                fileName = hostingEnv.WebRootPath + $@"\upload\{fileName}";
                size += file.Length;
                using (FileStream fs = System.IO.File.Create(fileName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }
            ViewBag.Message = $"{files.Count}个文件 /{size}字节上传成功!";
            return View("Index");
        }
    }
}
